import React, {
	PureComponent
} from 'react'
import { connect } from 'dva'
import { Form, Input, Button } from 'antd'
import Grid from '@/components/Grid'
import Dialog, { withRef } from '@/components/Dialog'
import settings, { getPagination } from '@/settings'
import { $request, $http } from '@/utils/request'
import Authorized from '@/components/Authorized'

@Form.create()
@connect(({ unit: { data } }) => ({ data }))
@withRef
class ModelForm extends React.Component {
	formLayout = {
		// labelAlign: 'left',
		// labelCol: {
		// 	span: 5
		// },
		// wrapperCol: {
		// 	span: 19
		// },
	};
	componentDidMount() {
		const {
			id,
			dispatch
		} = this.props;

		if (id) {
			dispatch({
				type: 'unit/fetchOne',
				payload: {
					id
				}
			});
		}
	};
	handleSubmit = (_, callback) => {
		const {
			form
		} = this.props

		form.validateFields((err, values) => {
			if (!err) {
				callback(values)
			}
		})
	};
	render() {
		const {
			id,
			data = {},
			form: {
				getFieldDecorator
			}
		} = this.props

		return (
			<Form layout="vertical">
	          <Form.Item label="部门名称" {...this.formLayout}>
	            {getFieldDecorator('name', {
					rules: [{
						required: true,
						message: '请输入部门名称'
					}, {
						validator: (rule, value, callback) => {
							$http.post('valid/rolename', {
								data: {
									id,
									value
								},
								type: true,
								requestType: 'form'
							}).then(data => {
								data.valid ? callback() : callback("部门名称已存在")
							})
						}
					}],
	              	initialValue: data.name,
	            })(<Input placeholder="请输入" />)}
	          </Form.Item>
	          <Form.Item {...this.formLayout} label="部门描述">
	            {getFieldDecorator('desc', {
					rules: [{
						message: '请输入至少五个字符的部门描述！',
						min: 5
					}],
	              	initialValue: data.desc,
	            })(<Input.TextArea rows={8} placeholder="请输入至少五个字符" />)}
	          </Form.Item>
	        </Form>
		)
	}
}

@connect(({
	app: {
		user = {}
	},
	unit: {
		list = {},
		params
	},
	loading
}) => ({
	user,
	list,
	params,
	loading: loading.effects['unit/fetchAll'],
}))
@Form.create()
class UnitPage extends PureComponent {
	state = {
		selectedRows: []
	};
	columns = [{
		title: '部门名称',
		dataIndex: 'name',
		width: 200
	}, {
		title: '描述',
		dataIndex: 'desc',
		width: 300
	}, {
		title: '创建时间',
		dataIndex: 'crtime',
		width: 150,
		align: 'center'
	}];
	componentDidMount() {
		const {
			dispatch
		} = this.props;
		dispatch({
			type: 'unit/fetchAll',
		});
	};
	handleSelectRows = rows => {
		this.setState({
			selectedRows: rows,
		});
	};
	handleAdd = e => {
		const {
			dispatch
		} = this.props;
		dispatch({
			type: 'unit/reset'
		});
		Dialog.open({
			title: '新建角色',
			component: ModelForm,
			url: 'unit/add',
			onOk: data => {
				this.handleReload()
			}
		})
	};
	handleEdit = e => {
		const { selectedRows } = this.state;
		const { id } = selectedRows[0];
		const {
			dispatch
		} = this.props;
		dispatch({
			type: 'unit/reset'
		});
		Dialog.open({
			title: '修改角色',
			url: 'unit/update',
			data: {
				id
			},
			options: {
				type: 'put'
			},
			onOk: data => {
				this.handleReload()
			},
			component: props => (<ModelForm {...props} id={id} />),
			connect: ({ loading }) => ({ loading: loading.effects['unit/fetchOne'] })
		})
	};
	handleRemove = e => {
		const { selectedRows } = this.state;
		Dialog.confirm({
			title: '确认提示',
			content: '确定要删除已选择的部门？',
			onOk: () => {
				$request.put('unit/delete', {
					data: {
						ids: selectedRows.map(_ => _.id)
					}
				}).then(data => {
					this.handleReload()
				})
			}
		})
	};
	handleGridChange = (oldPagination, sorter) => {
		const { params, dispatch } = this.props;
		
		const pagination = getPagination(oldPagination)
		const payload = {
			...params,
			...pagination
		}

		if (sorter.field) {
			payload.sorter = sorter.field
			payload.order = sorter.order
		}

		dispatch({
			type: 'unit/fetchAll',
			payload,
		})
	};
	handleReload = () => {
		const { params, dispatch } = this.props;
		dispatch({
			type: 'unit/fetchAll',
			payload: params
		})
	};
	handleSearch = (value, e) => {
		e.preventDefault();
		const { params, dispatch } = this.props;
		const pagination = getPagination({
			pageNumber: 1
		})
		dispatch({
			type: 'unit/fetchAll',
			payload: {
				...params,
				...pagination,
				name: value
			}
		})
	};
	render() {
		const { selectedRows } = this.state;
		const {
			user: {
				authorities = []
			},
			params,
			// form: {
			// 	getFieldDecorator
			// },
			loading,
			list: {
				data,
				total
			}
		} = this.props

		const pageNumber = params[settings.pageNumber]
		return (
			<div className="x-wrap">
				{/*<div className="x-header">
					<div className="x-title"><span className="title-text">用户管理</span></div>
				</div>*/}
				<div className="x-panel">
					<div className="x-toolbar">
						<div className="fl">
							<Authorized authorities={authorities} authority="ORG_ADD"><Button type="primary" onClick={this.handleAdd}>新建</Button></Authorized>
							<Authorized authorities={authorities} authority="ORG_EDIT"><Button onClick={this.handleEdit} disabled={selectedRows.length !== 1}>编辑</Button></Authorized>
							<Authorized authorities={authorities} authority="ORG_DEL"><Button type="danger" disabled={selectedRows.length === 0} onClick={this.handleRemove}>删除</Button></Authorized>
						</div>
						<div className="fr x-query">
							<Form layout="inline">
								<Input.Search placeholder="请输入要查询的关键词" onSearch={this.handleSearch} />
							</Form>
						</div>
					</div>
					<div className="x-fixed">
						<Grid 
						selectedRows={selectedRows} 
						onSelectRow={this.handleSelectRows} 
						columns={this.columns} 
						data={data}
						loading={loading}
						pagination={{
							pageNumber,
							total
						}}
						onReload={this.handleReload}
						onChange={this.handleGridChange} />
					</div>
				</div>
			</div>
		)
	}
}

export default UnitPage